<?php if ( ! defined('APPPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/
class mobile_controller extends PZ_Controller
{

	public function __construct() {
		parent::__construct();
	}

	public function beforeAction(){
		if(parent::beforeAction()){
			$this->mobile = $this->input->server('HTTP_PZMOBILE');
			if(!$this->mobile){
				$this->message('Error','Only Mobile can access this function');
				return false;
			}
			
			$this->noauthfunctions = array('checklogin','login','register','logout','sociallogin','category','socialregister','agreement');
			$this->adminfunctions = array('deletepin','banuser');
			if(!in_array($this->method , $this->noauthfunctions)&&!$this->islogin){
				$this->mobile_failed_response('needrelogin');
				return FALSE;
			}
			if(in_array($this->method , $this->adminfunctions)&&!($this->isadmin||$this->iseditor)){
				$this->mobile_failed_response(lang('illegal_operation','tip'));
				return FALSE;
			}
			return true;
		}
		return false;
	}
	
	public function agreement(){
		$this->output("mobile/agreement");
	}

	public function help(){
		$this->output("mobile/help");
	}

	public function contact_us(){
		$this->output("mobile/contact_us");
	}


	public function addreport(){
		$data['sid'] = $this->param('sid');
		$data['reason'] = $this->param('reason');
		$data['nickname'] = $this->cuser['email'];
		$emailapi = load_api('email');
		$emailapi->asyn_sendtoadmin('report',$data);
		$this->mobile_success_response(null,lang('200_operatesuccess','tip'));
	}

	public function banuser(){
		$uid = $this->param("uid");
		if($uid==$this->cuser['uid']){
			$this->mobile_failed_response(lang('500_cannot_bindself','tip'));
			return;
		}else if($uid===1){
			$this->mobile_failed_response(lang('500_cannot_bindcreator','tip'));
			return;
		}else{
			$userapi = load_api('user');
			$userapi->updateUserSystemGroupBP($uid);
			$shareapi = load_api('share');
			$shareapi->mvBannedUserPostToDeleted($uid);
			$this->mobile_success_response(null,lang('200_operatesuccess','tip'));
			return;
		}
	}
	public function deletepin(){
		$share_id = $this->param('sid');
		$shareapi = load_api('share');
		if($share_id){
			$share = $shareapi->getShareById($share_id);
		}
		if($share){
			$shareapi->deleteShareById($share_id);
			$this->mobile_success_response(null,lang('200_operatesuccess','tip'));
			return;
		}
		$this->mobile_failed_response(lang('500_operatefaild','tip'));
		return;
	}
	
	private function mobileinit(){
		$setting = load_api('setting')->getSetting('mobile');
		$data['note'] = lang('200_loginsuccess','tip');
		$data['albums'] = $this->initalbums();
		$data['user'] = $this->inituser();
		$data['setting'] = $setting;
		return $data;
	}
	
	private function initalbums(){
		$uapi = load_api('user');
		$user = $uapi->getUserInfo();
		$albumapi = load_api('album');
		$albums = $albumapi->getAlbumsByUser($user['uid'],false);
		foreach ($albums as $k=>$album){
			$albums[$k] = $albumapi->prepareAlbum($album);
		}
		return $albums;
	}

	private function inituser(){
		$uapi = load_api('user');
		$user = $uapi->getUserInfo();
		$user['avatar'] = useravatar($user['uid']);
		$user['isadmin'] = $uapi->isAdmin()?'true':'false';
		return $user;
	}
	
	public function checklogin(){
		if($this->islogin){
			$data = $this->mobileinit();
			$this->mobile_success_response($data, lang('200_loginsuccess','tip'));
		}else{
			$this->mobile_failed_response('needrelogin');
		}
		return;
	}


	public function user(){
		if($uid = $this->param('uid')){
			$user = load_api('user')->getUserWithGroupByid($uid);
			$user['avatar'] = useravatar($uid);
			$user['uid'] = $uid;
			$this->mobile_success_response($user);
			return;
		}

		$this->mobile_failed_response(lang('lost_param','tip'));
	}

	public function userfans(){
		$uid =  $this->param("uid");
		if(!$uid){
			$this->mobile_failed_response(lang('lost_param','tip'));
			return;
		}
		$this->output_user('fans', $uid);
	}


	public function userfollowing(){
		$uid =  $this->param("uid");
		if(!$uid){
			$this->mobile_failed_response(lang('lost_param','tip'));
			return;
		}
		$this->output_user('following', $uid);
	}

	private function output_user($action,$uid){
		$settingapi = load_api('setting');
		$setting = $settingapi->getSetting('layoutalbum');
		$num_per_page = $setting['uialbum_numperpage']?$setting['uialbum_numperpage']:20;

		$page = $this->param('page','1');
		if($action=='fans'){
			$conditions['friend_id'] = $uid;
			$fields = " user.* ";
		}else{
			$conditions['user_id'] = $uid;
			$fields = " friend.* ";
		}
			
		$users = load_db('user/userrel')->search($conditions,$page,$num_per_page,$fields);
		$users = $this->fillUserWithShare($users,$uid);
		$this->mobile_success_response($users);
	}

	private function fillUserWithShare($users,$user_id){
		$ptx_share = load_db('share');
		$shareapi = load_api('share');
		$ptx_relationship = load_db('user/userrel');
		foreach ($users as $key=>$user) {
			$users[$key]['uid'] = $user['user_id'];
			$s= $ptx_share->find_one(array('user_id'=>$user['user_id']));
			if($s) $users[$key]['share'] = $this->prepareshare($s);
			$users[$key]['status'] = $ptx_relationship->get_relation($this->cuser['uid'],$user['user_id']).'';
			if ($user['province']){
				$users[$key]['location'] = $user['province'].'-'.$user['city'];
			}else{
				$users[$key]['location'] = lang('earth');
			}
		}
		return $users;
	}


	public function userpins(){
		$uid =  $this->param("uid");
		if(!$uid){
			$this->mobile_failed_response(lang('lost_param','tip'));
			return;
		}
		$this->output_pin('userpins', " ptx_share.create_time DESC ",array('user_id'=>$uid));
	}

	public function userlikepins(){
		$uid =  $this->param("uid");
		if(!$uid){
			$this->mobile_failed_response(lang('lost_param','tip'));
			return;
		}

		$page = $this->param('page','1');
		$setting = load_api('setting')->getSetting('layoutpin');
		$pagesize = $setting['uipin_numperpage']?$setting['uipin_numperpage']:15;
		$args = array("page"=>"2");
		$conditions['user_id'] =$args['uid'] = $uid;
		$setting = load_api('setting')->getSetting('mobile');
		if(!$setting['showarticle']){
			$conditions['type']='noarticle';
		}
		$shareapi = load_api('share');
		$favsharedb = load_db('share/favshare');
		$shares = $favsharedb->search($conditions,$page,$pagesize,null,' ptx_share.create_time DESC ');
		if($shares){
			$shares = $this->prepareShares($shares);
		}

		$this->mobile_success_response($shares);
	}

	public function addfollow(){
		$friend_id = $this->param("fid");
		if(!is_numeric($friend_id)){
			$this->mobile_failed_response(lang('illegal_operation','tip'));
			return;
		}
		$userdb=load_db('user');
		$user = $userdb->find(array('user_id'=>$this->cuser['uid']),' ptx_user.total_follow ');
		if($user['total_follow']>=$this->memperm['maxfollow']&&!$this->isadmin&&!$this->iseditor){
			$this->mobile_failed_response(lang('reach_max_follow_num','tip').$this->memperm['maxfollow']);
			return;
		}

		$friend = $userdb->find(array('user_id'=>$friend_id));
		if(!$friend){
			$this->mobile_failed_response(lang('500_operatefaild','tip'));
			return;
		}
		$ptx_relationship = load_db('user/userrel');
		$result = $ptx_relationship->add_follow($this->cuser['uid'],$friend_id);
		if($result){
			$evtapi = load_api('event');
			$evtapi->follow($this->cuser['uid'],'',0,$share['user_id']);
			$evtapi->beenfollow($friend_id);
			$this->mobile_success_response($data, '');
			return;
		}else{
			$this->mobile_failed_response(lang('500_operatefaild','tip'));
			return;
		}
	}

	public function removefollow(){
		$friend_id = $this->param("fid");
		if(!is_numeric($friend_id)){
			$this->mobile_failed_response(lang('illegal_operation','tip'));
			return;
		}
		$ptx_relationship = load_db('user/userrel');
		$result = $ptx_relationship->remove_follow($this->cuser['uid'],$friend_id);
		if($result){
			$this->mobile_success_response($data, '');
			return;
		}else{
			$this->mobile_failed_response(lang('500_operatefaild','tip'));
			return;
		}
	}


	public function login(){
		if($data['email'] = $this->param('email')){
			$data['password'] = $this->param('password');
			$data['remember'] = true;
			$userapi = load_api('user');
			$result = $userapi->login($data);
			if($result===501){
				$this->mobile_failed_response(lang('501_password_wrong','tip'));
			}elseif($result===502){
				$this->mobile_failed_response(lang('502_user_notexist','tip'));
			}else{
				$data = $this->mobileinit();
				$this->mobile_success_response($data, lang('200_loginsuccess','tip'));
			}
			return;
		}
	}
	public function cemailcheck($postdata, $param){
		$userdb = load_db('user');
		return $userdb->checkemail($postdata);
	}

	public function cnicknamecheck($postdata, $param){
		$userdb = load_db('user');
		return $userdb->checknick($postdata);
	}
	public function register(){
		if($data['email'] = $this->param('email')){
			$data['nickname'] = $this->param('nickname');
			$password = $this->param('password');
			$data['is_active'] = 0;
			$fvalidation = load_class('Form_validation');

			$fvalidation->set_rules('email', 'lang:email:field' , 'trim|required|min_length[3]|valid_email|xss_clean|callback_cemailcheck');
			$fvalidation->set_rules('nickname', 'lang:nickname:field' , 'trim|required|min_length[2]|max_length[20]|xss_clean|callback_cnicknamecheck');
			$fvalidation->set_rules('password', 'lang:password:field' , 'trim|required|min_length[6]|max_length[40]');

			if ($fvalidation->run() == FALSE){
				$this->mobile_failed_response($fvalidation->error_string());
				return FALSE;
			}else{
				$userdb = load_db('user');
				$data["passwd"] = md5($password);
				if($this->ucopen){
					$uc_password = $password;
					$uc_username = strtolower($data['nickname']);
					$uc_email = strtolower($data['email']);
					$ucenter = load_api('ucenter');
					$uc_id = $ucenter->uc_user_register($uc_username, $uc_password, $uc_email);
					if($uc_id <= 0) {
						if($uc_id == -1) {
							$message = lang('500_nickname_invalid','tip');
						} elseif($uc_id == -2) {
							$message =lang('500_contain_invalid_word','tip');
						} elseif($uc_id == -3) {
							$message =lang('500_nickname_existed','tip');
						} elseif($uc_id == -4) {
							$message =lang('500_email_not_valid','tip');
						} elseif($uc_id == -5) {
							$message =lang('500_email_notallowed','tip');
						} elseif($uc_id == -6) {
							$message =lang('500_email_existed','tip');
						} else {
							$message =lang('500_unknown_faild','tip');
						}
						$this->ajax_failed_response($message);
						return FALSE;
					}

					$data['uc_id'] = $uc_id;
					$data['uc_nickname'] = $uc_username;
				}
					
				$user_id = $userdb->add_one($data);
				load_helper('view');
				create_default_avatar($user_id);
				$user = $userdb->getuser_byid($user_id);
				$user['password'] = $password;

				load_api('event')->register($user_id);
				load_api('user')->setsession($user);
				$data = $this->mobileinit();
				$this->mobile_success_response($data, lang('200_registersuccess','tip'));
				return TRUE;
			}
		}
		$this->mobile_failed_response(lang('lost_param','tip'));
	}

	public function logout(){
		$userapi = load_api('user');
		$result = $userapi->logout();
		$this->mobile_success_response(null, lang('200_logoutsuccess','tip'));
	}

	public function postshare(){
		if($postdata['album_id'] = $this->param('albumid')){
			$postdata['text'] = $this->param('describe');

			$file_name = $this->cuser['uid'].'_'.random(20).'';
			$date_dir = 'data/attachments/'.date("Y/m/d/");
			$save_path = BASEPATH . $date_dir;
			(!is_dir($save_path))&&@mkdir($save_path,0777,true);

			$upload_name = "Filedata";

			// Other variables
			$MAX_FILENAME_LENGTH = 260;
			//$file_name = "";
			$file_extension = "";
			$uploadErrors = array(
					0=>lang('upload_success','tip'),
					1=>lang('upload_exceed_phpini','tip'),
					2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
					3=>"The uploaded file was only partially uploaded",
					4=>"No file was uploaded",
					6=>"Missing a temporary folder"
			);
			// Validate the upload
			if (!isset($_FILES[$upload_name])) {
				log_message('error',"No upload found in \$_FILES for " . $upload_name);
				return;
			} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
				$this->template->content_display($uploadErrors[$_FILES[$upload_name]["error"]]);
				log_message('error',$uploadErrors[$_FILES[$upload_name]["error"]]);
				return;
			} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
				log_message('error',lang('upload_function','tip'));
				return;
			} else if (!isset($_FILES[$upload_name]['name'])) {
				log_message('error',lang('upload_no_filename','tip'));
				return;
			}

			// Validate the file size (Warning: the largest files supported by this code is 2GB)
			$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);

			if ($file_size <= 0) {
				log_message('error',lang('upload_size_exception','tip'));
				return;
			}

			// Validate file extension
			//$path_info = pathinfo($_FILES[$upload_name]['name']);
			//$file_extension = $path_info["extension"];
			$file_extension = strtolower(fileext($_FILES[$upload_name]['name']));

			$file_path = $save_path.$file_name.'.'.$file_extension;
			if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $file_path)) {
				log_message('error',lang('upload_save_faild','tip'));
				return;
			}
			$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';
			$db_file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));
			if (strlen($db_file_name) == 0 || strlen($db_file_name) > $MAX_FILENAME_LENGTH) {
				$db_file_name = $file_name.'.'.$file_extension;
			}

			$attdata['isimage']=in_array($file_extension, array('jpg','jpeg','png','gif'))?1:0;
			if($attdata['isimage']){
				$img_pro = @getimagesize($file_path);
				$attdata['width']=$img_pro['0'];
				$attdata['height']=$img_pro['1'];
			}
			$attdata['filename']=$db_file_name;
			$attdata['filesize']=$file_size;
			$attdata['attachment']=$date_dir.$file_name;
			$attdata['user_id']=$this->cuser['uid'];
			$attdata['fileext']=$file_extension;
			$attdata['remote']=0;
			$attdata['description']='';
			$attdata['thumb']=0;
			$attachfile = $date_dir.$file_name.'.'.$file_extension;
			$attapi = load_api('attachment');
			$aid = $attapi->insertUnused($attdata);

			$censorapi = load_api('censor');
			$txtresult = $censorapi->censor($postdata['text'],'***');
			if($txtresult){
				$this->mobile_failed_response($txtresult);
				return;
			}
			$adata=array();
			if($itemid = $this->prepareItem($postdata,false,$adata)){
				$results = array();
				if($att = $attapi->moveToReal($aid,$itemid,'',true)){
					$cover['findcover']=true;
					$cover['attachment']=$att['attachment'];
					$cover['fileext']=$att['fileext'];
					$cover['item_type']='image';
					$cover['share_type']=$this->mobile;
					$cover['aid']=$aid;
					$cover['width']=$att['width'];
					$cover['height']=$att['height'];
					$cover['total'] = 1;
				}

				if(load_api('share')->updateItem($cover, $itemid)){
					load_api('event')->afterpostshare($this->cuser['uid'],$postdata['text'],$itemid);
					$attapi->deleteUnusedByUser($this->cuser['uid']);
					load_api('album')->update_album_cover($postdata['album_id']);
				}
				load_db('user')->add_share($this->cuser['uid']);
				$this->mobile_success_response(array('note'=>lang('200_postsuccess','tip'),'share_id'=>$adata['share_id']), lang('200_postsuccess','tip'));
				return;
			}

		}

		$this->mobile_failed_response(lang('500_postfaild','tip'));
	}

	private function prepareItem($postdata,$isedit=false,&$data=array()){
		$puzzcode = load_api('puzzcode');
		$albumapi = load_api('album');

		$album = $albumapi->findAlbumByid($postdata['album_id']);

		$intro_search = $plaintxt = $puzzcode->parse_plain_message($postdata['text']);
		$msetting = load_api('setting')->getSetting('mobile');
		$setting = load_api('setting')->getSetting('share');
		$tagnum = $setting['tagnum'];
		if($msetting['verify']){
			$isshow = $this->sysperm['postverify']?'0':'1';
		}else{
			$isshow = '1';
		}
		$keyword = '';
		$nowtagnum = array_length(explode(' ', $keyword));
		if($nowtagnum<$tagnum){
			$tagapi = load_api('tag');
			$collected = $tagapi->collectFromTxt($album['category_id'],$plaintxt,$tagnum-$nowtagnum);
			if($collected['tag']) $collected_tag = join(' ', $collected['tag']);
			if($collected['search']) $collected_search = join(' ', $collected['search']);
			$keyword .= ' '.$collected_tag;
			$keyword_search .= ' '.$collected_search;
			$keyword = str_replace('  ', ' ', $keyword);
		}

		//$keyword_search = $keyword;
		if($this->isChineseVersion()){
			$segment = &load_class('Segment');
			//$keyword_search = $segment->convert_to_py($keyword_search);
			$segdb = $segment->getDbData($plaintxt);
			$keyword_search .= ' '.$segdb['keywordSearch'];

			$segment_str = $segment->segment($plaintxt);
			$intro_search = $segment_str['py'];
		}

		$parseat_str = $puzzcode->parse_at($postdata['text']);
		$parsetopic_str = $puzzcode->parse_topic($parseat_str['message']);
		if(!$isedit){
			$user = $this->cuser;
			$data['user_id']=$user['uid'];
			$data['user_nickname']=$user['nickname'];
		}
		$data['keyword']=$keyword;
		$data['keyword_search']=$keyword_search.' '.$parseat_str['atsearch_str'].' '.$parsetopic_str['search_str'];
		$data['color']='';
		$data['image_path_0']='';
		$data['image_path_1']='';
		$data['image_path_2']='';
		$data['width']='';
		$data['height']='';
		$data['item_type']='';
		$data['share_type']=$this->mobile;
		$data['price']=$postdata['price'];
		$data['is_show']=$isshow;
		$data['total_images']='';
		$data['title']=sysSubStr($plaintxt, 20, TRUE);
		$data['summary']=sysSubStr($plaintxt, 500, TRUE);

		$datadetail['intro']=$parsetopic_str['message'];
		$datadetail['intro_search']=$intro_search.' '.$parseat_str['atsearch_str'].' '.$parsetopic_str['search_str'];
		$datadetail['reference_url']=$postdata['url'];
		$datadetail['reference_itemid']='';
		$datadetail['promotion_url']='';

		if(!$isedit){
			$datashare['poster_id']=$user['uid'];
			$datashare['poster_nickname']=$user['nickname'];
			$datashare['user_id']=$user['uid'];
			$datashare['user_nickname']=$user['nickname'];
		}
		$datashare['category_id']=$album['category_id'];
		$datashare['album_id']=$postdata['album_id'];

		if($groupid = $this->param("groupid")){
			$this->group = load_db("group")->find_one(array('group_id'=>$groupid));
			if($this->group){
				$datadetail['intro_search'] .= ' group'.$groupid.'g';
				$data['keyword_search'] .= ' group'.$groupid.'g';
			}
		}

		if($storeid = $this->param("storeid")){
			$this->store = load_db("store")->find(array('store_id'=>$storeid));
			if($this->store){
				$datashare['store_id']=$storeid;
				$datashare['channel']=$this->param("storechannel",'review');
			}
		}

		$data['itemdetail'] = $datadetail;
		$data['sharedata'] = $datashare;

		$shareapi = load_api('share');
		if($isedit){
			return $shareapi->updateOriginalShare($postdata,$data)?$data:false;
		}else{
			return $shareapi->addOriginalShare($data);
		}
	}

	public function albums(){
		$settingapi = load_api('setting');
		$setting = $settingapi->getSetting('layoutalbum');

		$num_per_page = $setting['uialbum_numperpage']?$setting['uialbum_numperpage']:20;
		$data['user_id'] = $this->param('uid');
		$data['page'] = $this->param('page','1');
		$args = array("page"=>$data['page']+1);

		if($data['user_id']){
			$conditions['user_id'] = $data['user_id'];
		}

		$conditions['total_share_num'] = $setting['uialbum_minnum']?$setting['uialbum_minnum']:0;
		$api = load_api('album');
		$albums = $api->search($conditions,$data['page'],$num_per_page,' ptx_album.update_time DESC ');
		foreach ($albums as $k=>$album){
			$albums[$k] = $api->prepareAlbum($album);
			$albums[$k]['user_avatar'] = useravatar($album['user_id']);
			$albums[$k]['time'] =  delete_html(pgmdate($album['create_time']));
		}
		$this->mobile_success_response($albums);
	}

	public function detail(){
		$share_id = $this->param('sid');
		$shareapi = load_api('share');
		$share = $shareapi->getShareById($share_id);
		if($share){
			$shareapi->addviewnum($share_id);
			//$share['nextid'] = $shareapi->findnextid($share_id);
			//$share['preid'] = $shareapi->findprevid($share_id);
			$share['relation'] = load_db('user/userrel')->get_relation($this->cuser['uid'],$share['user_id']);
			$attaches = load_api('attachment')->findAttachByItem($share['item_id']);
			//$this->share_intro = load_api('puzzcode')->parse_message($this->share['intro'],$attaches,true);
			$imageattaches = array();
			$fileattaches = array();
			foreach ($attaches as $att){
				$att['url'] = base_url().$att['attachment'].'_large.'.$att['fileext'];
				if($att['isimage']){
					$att['PZ_CLASSTYPE'] = 'PZDetailImageViewCell';
					$imageattaches[] = $att;
				}else{
					$fileattaches[] = $att;
				}
			}
			$tags = trimarray(explode(' ', $this->share['keyword']));
			$clean = array();
			$maxtag = array_length($tags);
			$maxtag = $maxtag>10?10:$maxtag;
			for ($i=0;$i<$maxtag;$i++){
				$clean[] = $tags[$i];
			}
			unset($tags);
			$share['tags'] = $clean;
			$share['images'] = $imageattaches;
			$share['files'] = $fileattaches;
			if($share['reference_url']){
				$share['reflink'] = httpurl($share['reference_url']);
				$urls = parse_url($share['reflink']);
				$share['refhost'] = $urls['host'];
			}

			$comments = unserialize($share['comments']);
			$comments =($comments)?array_slice($comments,0,5):null;
			$puzzcodeapi = load_api('puzzcode');
			if($comments){
				foreach ($comments as $key=>$com){
					$comments[$key]['comment_txt'] = $puzzcodeapi->parse_plain_message($com['comment_txt']);
					$comments[$key]['user_avatar'] = useravatar($com['user_id']);
					$comments[$key]['time'] =  delete_html(pgmdate($com['create_time']));
				}
				$share['comments'] = $comments;
			}
			//$gshares = $shareapi->getRoundByCategory($share['category_id'],30);
			//$share['guess'] = $this->prepareShares($gshares);
			$share['user_avatar'] = useravatar($share['user_id']);
			$share['PZ_CLASSTYPE'] = 'PZDetailUserViewCell';
			$share['time'] = delete_html(pgmdate($share['create_time']));
			$share['intro'] = load_api('puzzcode')->parse_plain_message($share['intro']);
			$share['editperm'] = ($share['user_id']==$this->cuser['uid']||$this->isadmin||$this->iseditor);

			$favsharedb = load_db('share/favshare');
			$liked = $favsharedb->find(array('share_id'=>$share_id,'user_id'=>$this->cuser['uid']));
			if($liked){
				$share['status']='liked';
			}else{
				$share['status']='noliked';
			}

			$this->mobile_success_response($share);
		}else{
			$this->mobile_failed_response(lang('404_error_heading','tip'));
		}
	}

	public function guess(){
		$page = $this->param('page','1');
		$share_id = $this->param('sid');
		$category_id = $this->param('cid');
		if($page==='1'){
			$shareapi = load_api('share');
			$gshares = $shareapi->getRoundByCategory($category_id,30);
			$shares = $this->prepareShares($gshares);
			$this->mobile_success_response($shares);
		}else{
			$this->mobile_success_response(array());
		}
	}

	public function discovery(){
		//$conditions['type'] = 'noarticle';
		$this->output_pin('discovery', " ptx_share.create_time DESC ",array());
	}

	private function output_pin($action,$order,$conditions=array()){
		$api = load_api('setting');
		$setting = $api->getSetting('layoutpin');
		$pagesize = $setting['uipin_numperpage']?$setting['uipin_numperpage']:15;

		$data['page'] = $this->param('page','1');
		$data['category_id'] = $this->param('catid');
		$data['subcategory_id'] = $this->param('subcat');
		$args = array("page"=>$data['page']+1);

		// 		if($data['page'] == 1){
		// 			$guide['show'] = true;
		// 			if($data['category_id']){
		// 				$categoryapi = load_api('category');
		// 				$category = $categoryapi->getCategoryByid($data['category_id']);
		// 				$guide['subcats'] = $categoryapi->getSubCategories($data['category_id']);
		// 				$guide['hottags'] = $categoryapi->getCategoryHotTags($data['category_id']);
		// 			}
		// 			$data['guide'] = $guide;
		// 		}

		if($data['category_id']){
			if($data['subcategory_id']){
				$conditions['category_id'] = $data['subcategory_id'];
				$args['subcat']=$data['category_id'];
			}else{
				if($guide['subcats']){
					$conditioncats[] = $data['category_id'];
					foreach ($guide['subcats'] as $sub){
						$conditioncats[] = $sub['category_id'];
					}
					$conditions['category_in'] = $conditioncats;
				}else{
					$conditions['category_id'] = $data['category_id'];
				}
			}
			$args['catid']=$data['category_id'];
		}
		if($tag = $this->param('tag')){
			$tagafter = pzxdecode($tag);
			$conditions['keyword'] = $args['tag'] = $tag;
			$data['tag'] = $tagafter;
		}
		if($cdx = $this->param('cdx')){
			$args['cdx'] = $cdx;
		}
		if($keyword= $this->param('keyword')){
			if($this->isChineseVersion()){
				$keyword = safeEncoding($keyword);
			}
			$conditions['keyword'] = pzxencode($keyword);
			$args['keyword']=$keyword;
		}
		if($setting['uipin_showforward']){
			$conditions['orgin_post']=1;
		}

		$setting = load_api('setting')->getSetting('mobile');
		if(!$setting['showarticle']){
			$conditions['type']='noarticle';
		}

		$shareapi = load_api('share');
		$shares = $shareapi->search($conditions,$data['page'],$pagesize,$order);
		$shares = $this->prepareShares($shares);
		$this->mobile_success_response($shares);
	}

	private function prepareShares($shares){
		$settingapi = load_api('setting');
		$setting = load_api('setting')->getSetting('upload');
		$this->wftwidth = $setting['wftwidth'];
		$this->colorsetting = $settingapi->getSetting('colorindex');
		foreach ($shares as $key=>$share){
			$shares[$key] = $this->prepareshare($share);
		}
		return $shares;
	}

	private function prepareshare($share){
		$share['link'] = site_url('detail/index?shareid='.$share['share_id']);
		$share['muilt'] = ($this->uimuilt&&$share['image_path_0']&&$share['image_path_1']&&$share['image_path_2']);
		$share['image0'] = thumburl($share['image_path_0'],'middle',$share['cloud']);
		$share['image1'] = thumburl($share['image_path_1'],'square',$share['cloud']);
		$share['image2'] = thumburl($share['image_path_2'],'square',$share['cloud']);
		$share['square'] = thumburl($share['image_path_0'],'square',$share['cloud']);
		$share['large'] = thumburl($share['image_path_0'],'large',$share['cloud']);
		$share['home'] = thumburl($share['image_path_0'],'home',$share['cloud']);
		$share['avatar'] = useravatar($share['user_id']);
		$share['uid'] = $share['user_id'];
		$share['colorvalue'] = $this->colorsetting[$share['color']]?$this->colorsetting[$share['color']]:$this->colorsetting['gray'];
		if($share['reference_url']){
			$share['reflink'] = httpurl($share['reference_url']);
			$urls = parse_url($share['reflink']);
			$share['refhost'] = $urls['host'];
		}else{
			$share['refhost'] = $share['share_type'];
		}
		$share['isarticle'] = ($share['item_type']=='article')?true:false;
		$share['isvideo'] = ($share['item_type']=='video')?true:false;
		if(($share['item_type']=='article')){
			$share['PZ_CLASSTYPE'] = 'PZWaterfallTxtCell';
		}else{
			$share['PZ_CLASSTYPE'] = 'PZWaterfallCell';
		}

		if($share['price']){
			$share['price'] = $this->settings['priceunit'].$share['price'];
		}


		if(!$share['isarticle']){
			$share['summary'] = $share['summary']?sysSubStr($share['summary'], 100):'';
		}

		if($this->cuser['uid']==$share['user_id']){
			$share['isowner'] = true;
		}

		return $share;
	}

	//*********************************Social login functions**********************************************************

	public function xxxsociallogin(){
		$openid = $this->param("openid");
		$nickname = $this->param("nickname");
		$avatar = $this->param("avatar");
		$gender = $this->param("gender");
		$accessToken = $this->param("accessToken");
		$expirationDate = $this->param("expirationDate");
		$vendor = $this->param("vendor");
		$location = $this->param("location");
		$description = $this->param("description");

		$connectdb = load_db('social/connector');
		$userdb = load_db('user');
		$userapi = load_api("user");

		$social_connector = $connectdb->get_bind_by_vendor_and_suid($vendor,$openid);
		if($social_connector){
			$update_connect_data['avatar'] = $avatar;
			$connectdb->update(array('connect_id'=>$social_connector['connect_id']),$update_connect_data);
			$local_user = $userapi->getUserByid($social_connector['user_id']);
			$userapi->setsession($local_user);
			$data = $this->mobileinit();
			$this->mobile_success_response($data, lang('200_loginsuccess','tip'));
		}else{

			load_helper('string');
			$data['email'] = $this->param("email")?$this->param("email") : md5(random_string('alnum', 5)).'@'.config_item('default_domain');
			$data['nickname'] = $userdb->create_random_nick($nickname);
			//$data['avatar_remote'] = $social_user_info['avatar'];
			$data['gender'] = $gender;
			$data['location'] = $location;
			$data['bio'] = $description;
			$password = random_string('alnum', 8);
			$data['passwd'] = md5($password);
			$data['create_time'] = TIMESTAMP;
			$data['is_social'] = 1;
			$uid = $userdb->add_one($data);

			$connector_data['user_id'] = $uid;
			$connector_data['social_userid'] = $openid;
			$connector_data['vendor'] = $vendor;
			$connector_data['vendor_info'] = serialize(array('accesstoken'=>$accessToken,'expirationDate'=>$expirationDate));
			$connector_data['username'] = $nickname;
			$connector_data['name'] = $this->param('name');
			$connector_data['description'] = $description;
			$connector_data['homepage'] = $this->param("url");
			$connector_data['avatar'] = $avatar;
			$connector_data['email'] = $this->param("email");
			$connector_data['gender'] = $gender;
			$connector_data['location'] = $location;
			$connectdb->create($connector_data);

			$this->save_remote_avatar($avatar, $uid);
			load_api('event')->register($uid,true);
			$data['password'] = $password;
			$data['remember'] = true;
			$userapi->setsession($data);
			$data = $this->mobileinit();
			$this->mobile_success_response($data, lang('200_loginsuccess','tip'));
		}
	}


	public function xxsociallogin(){
		$openid = $this->param("openid");
		$nickname = $this->param("nickname");
		$avatar = $this->param("avatar");
		$accessToken = $this->param("accessToken");
		$expirationDate = $this->param("expirationDate");
		$vendor = $this->param("vendor");
		$data = array("email"=>uniqid(mt_rand()).'@shouxin.me',"nickname"=>$nickname,"password"=>"shouxin.me","is_active"=>"1","is_social"=>"1","user_type"=>"1");
		$vendor = 'qq';
		$ptx_connector = spClass("ptx_connector");
		$ptx_user = spClass('ptx_user');
		$social_connector = $ptx_connector->get_bind_by_vendor_and_suid($vendor,$openid);
		if($social_connector){
			$user = $ptx_user->getuser_byid($social_connector['user_id']);
			$this->mobile_success_response(array('uid'=>$user['user_id'],'avatar'=>useravatar($user['user_id'], 'middle'),'nickname'=>$user['nickname']), '');
		}else{
			if($userid = $ptx_user->register($data)){
				$connector_data['user_id'] = $userid;
				$connector_data['social_userid'] = $openid;
				$connector_data['vendor'] = $vendor;
				$connector_data['vendor_info'] = serialize(array('accesstoken'=>$accessToken,'expirationDate'=>$expirationDate));
				$connector_data['username'] = $nickname;
				$connector_data['avatar'] = $avatar;
				$ptx_connector->create($connector_data);
				$this->save_remote_avatar($avatar, $userid);
				$this->mobile_success_response(array('uid'=>$userid,'avatar'=>useravatar($userid, 'middle'),'nickname'=>$nickname), '');
			}else{
				$this->mobile_failed_response('login faild');
			}
		}
	}

	private function save_remote_avatar($url,$uid){
		$content = get_contents($url);
		$ptx_user = load_db('user');
		$avaorgin = useravatarpath($uid,false);
		$avalarge = useravatarpath($uid,'large');
		$avamiddle = useravatarpath($uid,'middle');
		$avasmall = useravatarpath($uid,'small');
		$avatardir = BASEPATH.useravatardir($uid);
		(!is_dir($avatardir))&&@mkdir($avatardir,0777,true);
		file_exists(BASEPATH.$avaorgin) && unlink(BASEPATH.$avaorgin);
		file_exists(BASEPATH.$avalarge) && unlink(BASEPATH.$avalarge);
		file_exists(BASEPATH.$avamiddle) && unlink(BASEPATH.$avamiddle);
		file_exists(BASEPATH.$avasmall) && unlink(BASEPATH.$avasmall);

		$imagepath = BASEPATH.$avaorgin;
		if(!empty($content) && @file_put_contents($imagepath,$content) > 0){
			$imagelib =  &load_class('ImageLib');
			$imagelib->create_thumb($imagepath,NULL,150,150,BASEPATH.$avalarge);
			$imagelib->create_thumb($imagepath,NULL,50,50,BASEPATH.$avamiddle);
			$imagelib->create_thumb($imagepath,NULL,16,16,BASEPATH.$avasmall);
			return true;
		}else{
			load_helper('view');
			create_default_avatar($user_id);
			return true;
		}
		return false;
	}
	//******************category functions***********************************
	public function category(){
		$categoryapi = load_api('category');
		$cates = $categoryapi->getCleanCategoryTree();
		$category['category_id'] = '0';
		$category['category_name_cn'] = lang('lastest','mobile');
		$category['category_name_en'] = 'Lastest';
		$category['tags'] = array(lang('lastest_tip','mobile'));
		$cates = array_merge(array($category),$cates);
		$this->mobile_success_response(array('category'=>$cates,'tag'=>null), '');
	}

	//******************pin functions***********************************
	public function addlike(){

		$share_id = $this->param('sid');
		$shareapi = load_api('share');
		$result = $shareapi->addlike($share_id,$this->cuser['uid']);
		if($result===true){
			$this->mobile_success_response('liked', lang('200_postsuccess','tip'));
		}else if($result=='like_self'){
			$this->mobile_failed_response(lang('500_likeself','tip'));
		}else if($result=='like_already'){
			$shareapi->removelike($share_id,$this->cuser['uid']);
			$this->mobile_success_response('removelike');
		}else{
			$this->mobile_failed_response('Add Like Faild');
		}

	}

	function postcomment(){
		if(!$this->sysperm['allowcomment']){
			$this->mobile_failed_response(lang('nopermission','tip'));
			return;
		}
		$comment = delete_html($this->param('comment'));
		$share_id = $this->param('sid');
		$fvalidation = load_class('Form_validation');
		$fvalidation->set_rules('comment', 'lang:comment:field' , 'trim|required|max_length[210]|xss_clean');
		if ($fvalidation->run() == FALSE){
			$this->mobile_failed_response($fvalidation->error_string());
			return FALSE;
		}

		$shareapi = load_api('share');
		$share = $shareapi->getShareById($share_id);
		if (!$comment||!$share) {
			$this->ajax_failed_response(lang('500_postfaild','tip'));
			return;
		}
		$puzzcode = load_api('puzzcode');
		$at_array = $puzzcode->parse_at($comment);
		$new_comment['comment_txt'] = $at_array['message'];
		$new_comment['search_en'] = ' '.$at_array['atsearch_str'];
		$new_comment['share_id'] = $share_id;
		$new_comment['user_id'] = $this->cuser['uid'];
		$new_comment['create_time'] = TIMESTAMP;

		$commentapi = load_api('comment');
		if ($new_comment['comment_id'] = $commentapi->addcomment($new_comment)) {
			$new_comment['nickname'] = $this->cuser['nickname'];
			$new_comment['user_avatar'] = useravatar($this->cuser['uid'], 'middle');
			$new_comment['time'] = delete_html(pgmdate(TIMESTAMP));
			$new_comment['comment_txt'] = $puzzcode->parse_plain_message($new_comment['comment_txt']);
			$new_comment['delete'] = true;

			if($this->cuser['uid']!=$share['user_id']){
				load_api('event')->postcomment($this->cuser['uid'],$share['title'],$share_id,$share['user_id']);
			}
			$this->mobile_success_response($new_comment, lang('200_postsuccess','tip'));
			return ;
		}else{
			$this->mobile_failed_response(lang('500_postfaild','tip'));
			return ;
		}
	}

	//*********************************album functions*********************************

	public function albumpins(){
		$album_id =  $this->param("aid");
		if(!$album_id){
			$this->mobile_failed_response(lang('lost_param','tip'));
			return;
		}
		$this->output_pin('albumpins', " ptx_share.create_time DESC ",array('album_id'=>$album_id));
	}

	public function createalbum(){
		$count = load_api('album')->getalbumnumbyuid($this->cuser['uid']);
		if($count>=$this->memperm['maxalbum']&&!$this->isadmin&&!$this->iseditor){
			$this->mobile_failed_response(lang('reach_create_maxnum','tip').$this->memperm['maxalbum']);
			return;
		}
		if($data = $this->update_album_common()){
			$api = load_api('album');
			if($album = $api->addAlbum($data)){
				//$album['url'] = base_url().site_url('home/albumshare?aid='.$album['album_id']);

				$data['albums'] = $this->initalbums();
				$data['user'] = $this->inituser();
				$this->mobile_success_response($data, lang('200_operatesuccess','tip'));
			}else{
				$this->mobile_failed_response(lang('500_operatefaild','tip'));
			}
		}
	}

	public function albumupdate(){
		$album_id =  $this->param("aid");
		if(!$album_id){
			$this->mobile_failed_response(lang('lost_param','tip'));
			return;
		}
		$albumapi = load_api("album");
		if($data['album'] = $albumapi->findAlbumByid($album_id)){
			if($data['album']['user_id']!=$this->cuser['uid']){
				$this->mobile_failed_response(lang('illegal_operation','tip'));
				return;
			}
		}else {
			$this->mobile_failed_response(lang('illegal_operation','tip'));
			return;
		}

		$act = $this->param("act");
		if($act=='edit'){
			if($updata = $this->update_album_common()){
				if(load_db('album')->update(array('album_id'=>$album_id),$updata)){
					$this->mobile_success_response(array(), lang('200_operatesuccess','tip'));
					return;
				}else{
					$this->mobile_failed_response(lang('500_operatefaild','tip'));
					return;
				}
			}
		}elseif($act=='delete'){
			if($albumapi->deletealbum($album_id)){
				$this->mobile_success_response(array(), lang('200_operatesuccess','tip'));
				return;
			}else{
				$this->mobile_failed_response(lang('500_operatefaild','tip'));
				return;
			}
		}else {
			$this->mobile_success_response($data);
		}
	}

	public function albumcheck($postdata, $param){
		return load_api('album')->albumcheck($postdata, $param);
	}

	public function update_album_common($act="update"){
		$album_title =  trim($this->param("album_title"));
		$album_desc =  trim($this->param("album_desc",''));
		$category_id =  trim($this->param("category_id"));
		$fvalidation = load_class('Form_validation');
		if($act=='update'){
			$fvalidation->set_rules('album_title', 'lang:album_title:field' , 'trim|required|min_length[1]|max_length[20]|xss_clean');
		}else{
			$fvalidation->set_rules('album_title', 'lang:album_title:field' , 'trim|required|min_length[1]|max_length[20]|xss_clean|callback_albumcheck');
		}
		$fvalidation->set_rules('album_desc', 'lang:album_desc:field' , 'trim|max_length[200]|xss_clean');
		$fvalidation->set_rules('category_id', 'lang:category_id:field' , 'trim|required');

		if ($fvalidation->run() == FALSE){
			$this->mobile_failed_response($fvalidation->error_string());
			return FALSE;
		}
		$data['album_title'] = $album_title;
		$data['album_desc'] = $album_desc;
		$data['category_id'] = $category_id;
		$data['user_id'] = $this->cuser['uid'];
		return $data;
	}


	public function sociallogin(){
		$postvar = array('nickname','avatar','openid','accessToken','expirationDate','vendor','email');
		foreach ($postvar as $key){
			$postdata[$key] = $this->param($key);
		}

		if($postdata['openid']&&$postdata['vendor']){
			$connectdb = load_db('social/connector');
			$userdb = load_db('user');
			$userapi = load_api("user");

			$social_connector = $connectdb->get_bind_by_vendor_and_suid($postdata['vendor'],$postdata['openid']);

			if($social_connector){
				if($this->cuser['uid']&&$social_connector['user_id']!=$this->cuser['uid']){
					$this->mobile_failed_response(lang('account_already_bind','social'));
					return;
				}else{
					$update_connect_data['avatar'] = $postdata['avatar'];
					//need update remote avatar
					$connectdb->update(array('connect_id'=>$social_connector['connect_id']),$update_connect_data);

					$local_user = $userapi->getUserByid($social_connector['user_id']);
					$userapi->setsession($local_user);
					$data = $this->mobileinit();
					$data['utype'] = 'olduser';
					$this->mobile_success_response($data, lang('200_loginsuccess','tip'));
				}
			}else{
				if($this->islogin){
					$connector_data['user_id'] = $this->cuser['uid'];
					$connector_data['social_userid'] = $postdata['openid'];
					$connector_data['vendor'] = $postdata['vendor'];
					$connector_data['vendor_info'] = serialize(array('accessToken'=>$postdata['accessToken'],'expirationDate'=>$postdata['expirationDate']));
					$connector_data['username'] = $postdata['nickname'];
					$connector_data['avatar'] = $postdata['avatar'];
					$connector_data['email'] = $postdata['email'];
					$connectdb->create($connector_data);
					$this->mobile_success_response($data, lang('200_operatesuccess','tip'));
				}else{
					$this->session = &load_class('Session');
					$this->session->put('social_info',$postdata);
					$data['utype'] = 'new';
					$data['social_info'] = $postdata;
					$this->mobile_success_response($data, lang('200_loginsuccess','tip'));
				}
			}


		}
	}

	public function socialregister(){
		$connectdb = load_db('social/connector');
		$userdb = load_db('user');
		$userapi = load_api("user");
		$this->session = &load_class('Session');
		$social_user_info = $this->session->get('social_info');
		$nickname = $this->param("nickname");
		if($social_user_info&&$nickname){
			if($userdb->checknick($nickname)){
				load_helper('string');

				if($social_user_info['email']&&($user = $userapi->getUserByEmail($social_user_info['email']))){
					$uid = $user['user_id'];
					$data=$user;
				}else{
					$data['email'] = $social_user_info['email']?$social_user_info['email']:md5(random_string('alnum', 5)).'@'.config_item('default_domain');
					$data['nickname'] = $nickname;
					//$data['avatar_remote'] = $social_user_info['avatar'];
					$data['gender'] = $social_user_info['gender'];
					$data['location'] = $social_user_info['location'];
					$data['bio'] = $social_user_info['description'];
					$password = random_string('alnum', 8);
					$data['passwd'] = md5($password);
					$data['create_time'] = TIMESTAMP;
					$data['is_social'] = 1;
					$uid = $userdb->add_one($data);
					$data['password'] = $password;
				}


				$connector_data['user_id'] = $uid;
				$connector_data['social_userid'] = $social_user_info['openid'];
				$connector_data['vendor'] = $social_user_info['vendor'];
				$connector_data['vendor_info'] = serialize(array('accessToken'=>$social_user_info['accessToken'],'expirationDate'=>$social_user_info['expirationDate']));
				$connector_data['username'] = $social_user_info['nickname'];
				$connector_data['name'] = $social_user_info['name'];
				$connector_data['description'] = $social_user_info['description'];
				$connector_data['homepage'] = $social_user_info['url'];
				$connector_data['avatar'] = $social_user_info['avatar'];
				$connector_data['email'] = $social_user_info['email'];
				$connector_data['gender'] = $social_user_info['gender'];
				$connector_data['location'] = $social_user_info['location'];
				$connectdb->create($connector_data);

				$this->save_remote_avatar($social_user_info['avatar'], $uid);
				load_api('event')->register($uid,true);
				$this->session->put('social_info','');
				$local_user = $userapi->getUserByid($uid);
				$userapi->setsession($local_user);
				$data = $this->mobileinit();
				$this->mobile_success_response($data, lang('200_loginsuccess','tip'));
				return;
			}else{
				$this->mobile_failed_response(lang('500_nickname_existed','tip'));
			}
		}
	}



	public function updateuserinfo(){
		if($this->param('nickname')){
			$data['nickname'] = trim($this->param('nickname'));
			$data['email'] = trim($this->param('email'));
			$userdb = load_db('user');
			if ($data['nickname']!=$this->cuser['nickname']&&!$userdb->checknick($data['nickname'])) {
				$this->mobile_failed_response(sprintf(lang('cnicknamecheck','form_validation'),$data['nickname']));
				return;
			}
			if($data['email']!=$this->cuser['email']&&!$userdb->checkemail($data['email'])){
				$this->mobile_failed_response(sprintf(lang('cemailcheck','form_validation'),$data['email']));
				return;
			}

			$tmppath = BASEPATH.'data/attachments/tmp/';
			$filename = $this->cuser['uid'].'_'.TIMESTAMP;
			if($avatar = $this->processupload($tmppath,$filename)){
				$avatar_dir = BASEPATH.useravatardir($this->cuser['uid']);
				(!is_dir($avatar_dir))&&@mkdir($avatar_dir,0777,true);
				$imagepath = $avatar['filepath'];

				if($name = substr($this->cuser['uid'], -2)){
					$filename = $name.'_avatar';
				}else{
					$filename = $this->cuser['uid'].'_avatar';
				}
				//$filename = substr($this->cuser['uid'], -2).'_avatar';
				$orgin = $avatar_dir.$filename.".jpg";
				$large = $avatar_dir.$filename."_large.jpg";
				$middle = $avatar_dir.$filename."_middle.jpg";
				$small = $avatar_dir.$filename."_small.jpg";
				file_exists($orgin) && unlink($orgin);
				file_exists($large) && unlink($large);
				file_exists($middle) && unlink($middle);
				file_exists($small) && unlink($small);

				@copy($imagepath, $orgin);
				$imagelib = &load_class('ImageLib');
				$imagelib->create_thumb($imagepath,NULL,150,150,$large);
				$imagelib->create_thumb($imagepath,NULL,50,50,$middle);
				$imagelib->create_thumb($imagepath,NULL,16,16,$small);
				unlink($imagepath);

				load_api('event')->setavatar($this->cuser['uid']);
			}

			$fvalidation = load_class('Form_validation');

			$fvalidation->set_rules('nickname', 'lang:nickname:field' , 'trim|required|min_length[2]|max_length[20]|xss_clean');

			if ($fvalidation->run() == FALSE){
				$this->mobile_failed_response($fvalidation->error_string());
				return FALSE;
			}else{
				if($userdb->update(array('user_id'=>$this->cuser['uid']),$data)){
					load_api('user')->forceRefreshLoginInfo();
					$data = $this->mobileinit();
					$this->mobile_success_response($data, lang('200_operatesuccess','tip'));
				}else{
					$this->mobile_failed_response(lang('500_operatefaild','tip'));
				}
			}
		}else{

			$this->mobile_failed_response(lang('500_operatefaild','tip'));
		}

	}

	//*********************************common functions********************************

	private function processupload($save_path,$file_name){
		$upload_name = "Filedata";

		// Other variables
		$MAX_FILENAME_LENGTH = 260;
		//$file_name = "";
		$file_extension = "";
		$uploadErrors = array(
				0=>lang('upload_success','tip'),
				1=>lang('upload_exceed_phpini','tip'),
				2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
				3=>"The uploaded file was only partially uploaded",
				4=>"No file was uploaded",
				6=>"Missing a temporary folder"
		);
		// Validate the upload
		if (!isset($_FILES[$upload_name])) {
			log_message('error',"No upload found in \$_FILES for " . $upload_name);
			return false;
		} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
			$this->template->content_display($uploadErrors[$_FILES[$upload_name]["error"]]);
			log_message('error',$uploadErrors[$_FILES[$upload_name]["error"]]);
			return false;
		} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
			log_message('error',lang('upload_function','tip'));
			return false;
		} else if (!isset($_FILES[$upload_name]['name'])) {
			log_message('error',lang('upload_no_filename','tip'));
			return false;
		}

		// Validate the file size (Warning: the largest files supported by this code is 2GB)
		$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);

		if ($file_size <= 0) {
			log_message('error',lang('upload_size_exception','tip'));
			return false;
		}

		// Validate file extension
		//$path_info = pathinfo($_FILES[$upload_name]['name']);
		//$file_extension = $path_info["extension"];
		$file_extension = strtolower(fileext($_FILES[$upload_name]['name']));

		$file_path = $save_path.$file_name.'.'.$file_extension;
		if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $file_path)) {
			log_message('error',lang('upload_save_faild','tip'));
			return false;
		}
		$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';
		$db_file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));
		if (strlen($db_file_name) == 0 || strlen($db_file_name) > $MAX_FILENAME_LENGTH) {
			$db_file_name = $file_name.'.'.$file_extension;
		}

		return array('dbfilename'=>$db_file_name,'filepath'=>$file_path,'fileext'=>$file_extension);

	}

	private function mobile_success_response($data,$message=''){
		$response = array('success' => 'true', 'data' => $data, 'message'=>$message);
		$content = json_encode($response);
		$this->template->content_display($content);
	}

	private function mobile_failed_response($message='failed_msg'){
		$response = array('success' => 'false','message'=>$message,'data'=>$data);
		$content = json_encode($response);
		$this->template->content_display($content);
	}



}

